package com.jiaomatech.tencent.cos.config;

import com.jiaomatech.tencent.cos.CosConstants;
import com.jiaomatech.tencent.cos.CosProperties;
import com.jiaomatech.tencent.cos.cos.MyCosClient;
import com.jiaomatech.tencent.cos.helper.CosHelper;
import com.jiaomatech.tencent.cos.resource.CosStorageProtocolResolver;
import com.qcloud.cos.COS;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * Description: 私有云cos自动配置 .<br>
 * ConditionalOnClass 参数中对应的类在 classpath 目录下存在时，才会去解析对应的配置类，否则不解析该注解修饰的配置类.
 * EnableConfigurationProperties 使 ConfigurationProperties 生效.
 * ConditionalOnProperty:
 * name - 数组，property完整名称或部分名称（可与prefix组合使用，组成完整的property名称），与value不可同时使用
 * havingValue - 可与name组合使用，比较获取到的属性值与havingValue给定的值是否相同，相同才加载配置
 * matchIfMissing - 缺少该property时是否可以加载。如果为true，没有该property也会正常加载；反之报错
 *
 * @author jm
 *     Created By 2018/9/27 上午10:47
 */
@Configuration
@ConditionalOnClass(COS.class)
@ConditionalOnProperty(
    name = CosConstants.ENABLED,
    havingValue = "true",
    matchIfMissing = true
)
@EnableConfigurationProperties(CosProperties.class)
@Import(CosProtocolResolverConfiguration.class)
public class CosAutoConfiguration {

    /**
     * 日志.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(CosAutoConfiguration.class);

    @ConditionalOnMissingBean
    @Bean
    public MyCosClient myCosClient(COSClient cosClient) {
        return new MyCosClient(cosClient);
    }

    @ConditionalOnMissingBean
    @Bean
    public COSClient cosClient(CosProperties cosProperties) {
        LOGGER.info("构建 COS 连接");
        COSCredentials cred = new BasicCOSCredentials(cosProperties.getAccessKeyId(), cosProperties
            .getSecretAccessKey());
        ClientConfig clientConfig = cosProperties.getClientConfig();
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }

    @ConditionalOnMissingBean
    @Bean
    public CosHelper cosHelper() {
        return new CosHelper();
    }
}
